import { fileURLToPath, URL } from 'node:url'
// import viteCompression from 'vite-plugin-compression';
import path from 'path'
import { defineConfig } from 'vite'
import copy from 'rollup-plugin-copy'
import vue from '@vitejs/plugin-vue'
import terser from '@rollup/plugin-terser';
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // viteCompression({
    //   verbose: true,
    //   disable: false,
    //   threshold: 10240,
    //   algorithm: 'gzip',
    //   ext: '.gz',
    // }),
  ],
  define: {
    'process.env.NODE_ENV': '"production"'
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      '@p': fileURLToPath(new URL('./packages', import.meta.url))
    }
  },
  build: {
    minify: false,
    outDir: "Ly-lib",
    lib: {
      formats: ['es'],
      entry: [path.resolve(__dirname, 'packages/index.ts')],
      fileName: (format, name) => `${name}.js`
    },
    rollupOptions: {
      plugins: [
        copy({
          targets: [
            { src: 'packages/type/index.d.ts', dest: 'public' },
            { src: 'packages/package.json', dest: 'public' },
            { src: 'packages/README.md', dest: 'public' },
          ]
        }),
        terser({
          ecma: 2020,
          compress: {
            // drop_console: false, // 保留 console 语句
            drop_debugger: true,
            // pure_funcs: ['console.log', 'console.info', 'console.warn', 'console.error'], // 保留特定的 console 方法
          },
          format: {
            comments: false, // 移除所有注释
            beautify: false,// 不格式化代码
            braces: false,// 不使用大括号
          },
        })
      ],

      output: {
        assetFileNames: (option) => {
          const strIndex = (option.source as string).indexOf('lastyear')
          let name = 'default'
          if (strIndex > -1) {
            const regex = /lastyear=([^\]]+)(?=])/;
            const match = (option.source as string).match(regex);
            name = match![0].split('=')[1]
          }
          return `${name}.css`
        }

      }
    }
  }
})
